%% Author: zhangjun
%% Created: 2008-11-28
%% Description: TODO: Add description to listtest
-module(listtest).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([start/1,mergezip/2,merge/2,foldf/2,mapf/2]).

%%
%% API Functions
%%

%%
%% TODO: Add description of start/function_arity
%%
start(_Arg0) -> 
	ok.

%%
%% Local Functions
%%
%classic code quick sort%
qsort([])  ->  [];
qsort([Pivot|T])  ->
	qsort([X  ||  X  <-  T,  X  <  Pivot])
	++  [Pivot]  ++
	qsort([X  ||  X  <-  T,  X  >=  Pivot]).


mergezip(L1, L2) when is_list(L1),is_list(L2) ->
    mergezip(L1,L1,0,L2,L2,0,[]).

mergezip([H1|R1],L1,N1,[H2|R2],L2,N2,Z) ->
    mergezip(R1,L1,N1,R2,L2,N2,[{H1,H2}|Z]);
mergezip([],_L1,_N1,[],_L2,_N2,Z) ->
    lists:reverse(Z);
mergezip(R1,L1,0,[],L2,N2,Z) ->
    mergezip(R1,L1,0,L2,L2,N2+1,Z);
mergezip(_R1,_L1,_N1,[],_L2,_N2,Z) ->
    lists:reverse(Z);
mergezip([],L1,N1,R2,L2,0,Z) ->
    mergezip(L1,L1,N1+1,R2,L2,0,Z);
mergezip([],_L1,_N1,_R2,_L2,_N2,Z) ->
    lists:reverse(Z).

merge(L1,L2) when is_list(L1),is_list(L2) ->
    merge(L1,L2,[]).

merge([],L2,Z) ->
    lists:reverse(Z) ++ L2;
merge(L1,[],Z) ->
    lists:reverse(Z) ++ L1;
merge([H1|R1],[H2|R2],Z) ->
    if
	H1 =< H2 ->
	    merge(R1,[H2|R2],[H1|Z]);
	true ->
	    merge([H1|R1],R2,[H2|Z])
    end.


%%foldf([in(Key,Val2), in(Key2,Val),....], DB).
%%in(K,V) -> fun(Db) -> in(K,V,Db) end.
%%in函数是对Db这个容器的操作函数，例如增删改查
%%Fs = [in(Key,Val2), in(Key2,Val),....]

foldf(Fs,Db) ->
    lists:foldl( fun(Fun, Acc) when is_function(Fun,1) ->
			 case catch (Fun(Acc)) of
			     {ok, Ret} ->
				 Ret;
			     Ret ->
				 throw ({exit,return_error,erlang:fun_info(Fun),Ret})
			 end;
			 
		    (_Fun,_Acc) ->
			    throw ({error,error_function_argumentnum})
		    end, Db, Fs).

mapf(Fs,Db) ->
    [ Fun(Db) || Fun<-Fs ].
